import requests
from lxml import etree
from urllib.parse import urljoin  # 用于拼接完整URL
import time

url = 'http://angelimg.spbeen.com'

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Referer": "http://angelimg.spbeen.com/",  # 可以指向一个更具体的来源页
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
    "Connection": "keep-alive"
}

try:
    response = requests.get(url, headers=headers, timeout=10)
    response.raise_for_status()  # 如果状态码不是200，抛出异常
except requests.exceptions.RequestException as e:
    print(f"请求主页失败: {e}")
    exit()

html = etree.HTML(response.text)
image_links = html.xpath('.//img/@src')

for index, link in enumerate(image_links, start=1):
    # 拼接完整URL
    full_link = urljoin(url, link)
    imagename = link.split('/')[-1]
    filename = f"{index}_{imagename}"
    # print("链接为：", full_link)

    try:
        # 再次请求图片资源，设置超时
        image_response = requests.get(full_link, headers=headers, timeout=15)
        image_response.raise_for_status()  # 确保图片请求成功
        # print(full_link)
        # 检查内容类型是否为图片
        content_type = image_response.headers.get('Content-Type', '')
        if not content_type.startswith('image'):
            print(f"{index} 错误: 返回的不是图片内容 (Content-Type: {content_type}), 链接: {full_link}")
            continue

        # 写入文件
        with open(filename, 'wb') as f:
            f.write(image_response.content)
        print(f"{index} 成功下载: {filename} from {full_link}")

    except requests.exceptions.RequestException as e:
        print(f"{index} 请求图片失败: {full_link}, 错误: {e}")
    except IOError as e:
        print(f"{index} 文件写入失败: {filename}, 错误: {e}")
    except Exception as e:
        print(f"{index} 发生未知错误: {e}")

    # 可选的：添加短暂延迟以减轻服务器压力
    time.sleep(0.5)